using Mysolution.Domain.Entities;
using Mysolution.Domain.Repositories;
using Mysolution.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Mysolution.Infrastructure.Repositories;

public class EfRepository<T> :IRepository<T> where T :EntityBase
{
    private readonly MysolutionDbContext _db;
    private readonly DbSet<T> _tb;
    public EfRepository(MysolutionDbContext db)
    {
        _db=db;
        _tb=_db.Set<T>();
    }
        public async Task<T> CreateAsync(T entity)
    {
        var obj = await _tb.AddAsync(entity);
        await _db.SaveChangesAsync();
        return obj.Entity;
    }

    public async Task DeleteAsync(T entity)
    {
        // _tb.Remove(entity);
        entity.IsDeleted = true;
        await UpdateAsync(entity);
    }

    public async Task<IEnumerable<T>> GetAllAsync()
    {
        var list = await _tb.AsNoTracking().ToListAsync();
        return list;
    }

    public async Task<T?> GetByIdAsync(Guid id)
    {
        var obj = await _tb.FindAsync(id);

        return obj;
    }

    public async Task UpdateAsync(T entity)
    {
        entity.UpdatedAt = DateTime.UtcNow;
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }
}